package com.lxx.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxx.common.ErrCode;

public class ResponseUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(ResponseUtils.class);
	
	public static final void writeJson(HttpServletResponse response, String json){
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		
		try(PrintWriter writer = response.getWriter();){
			
			writer.print(json);
			writer.flush();
			
		}catch(IOException e){
			LOGGER.error("response error:",e);
		}
	}
	
	public static final void writeJson(HttpServletResponse response, ErrCode errCode){
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		
		try(PrintWriter writer = response.getWriter();){
			
			writer.print(JSON.toJSONString(errCode.toMap()));
			writer.flush();
			
		}catch(IOException e){
			LOGGER.error("response error:",e);
		}
	}

	/**
	 * 往相应头中写内容
	 * @param errCode
	 */
	public static final void writeJson2Header(HttpServletResponse response, ErrCode errCode) {
		response.addHeader(Constant.RESPONSE_HEADER_CODE_NAME, Integer.toString(errCode.getCode()));
	}
	
	public static final void writeBytes(HttpServletResponse response, byte[] data) {
		try {
			OutputStream os = response.getOutputStream();
			os.write(data);
			os.flush();
			os.close();
		} catch (IOException e) {
			LOGGER.error("",e);
		}
	}
}
